package manager.modulo.orcamento.fonte;

import java.awt.event.KeyEvent;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.LinkedList;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.table.TableRowSorter;
import manager.auxiliares.AutoComplete;
import manager.auxiliares.Configurations;
import manager.auxiliares.FixedLengthDocument;
import manager.auxiliares.Format;
import manager.auxiliares.Icons;
import manager.auxiliares.ImprimirTabela;
import manager.auxiliares.MensagemExcessao;
import manager.auxiliares.WindowsFunctions;
import manager.helpers.table.TableModel;
import manager.helpers.table.TableRender;
import manager.helpers.table.TableRowComparator;
import manager.helpers.validation.FormatedFieldValidator;
import manager.helpers.validation.TextFieldValidator;
import manager.helpers.validation.ValidationFunctions;
import manager.principal.fonte.JanelaLogin;
import manager.interfaces.InterfaceTable;
import manager.modulo.clientefornecedor.dao.ClienteFornecedorDao;
import manager.modulo.estoque.dao.ComposicaoDao;
import manager.modulo.estoque.dao.ItemComposicaoDao;
import manager.modulo.estoque.dao.InsumoDao;
import manager.modulo.estoque.enumerator.EnumTipoInsumo;
import manager.modulo.estoque.enumerator.EnumUnidadeInsumo;
import manager.modulo.orcamento.dao.InsumoOrcamentoDao;
import manager.modulo.orcamento.dao.ItemOrcamentoDao;
import manager.modulo.orcamento.dao.OrcamentoDao;
import manager.modulo.orcamento.enumerator.EnumTipoItemOrcamento.TipoItemOrcamento;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.view.JasperViewer;

/**
 *
 * @author Thiago
 */
public class JanelaOrcamento extends javax.swing.JFrame {

    //Entrada de Estoque
    int idOrcamento = 0;
    int indiceTabelaItemOrcamento = 0;
    int indiceTabelaInsumoOrcamento = 0;
    TableModel tableModelItemOrcamento;
    TableModel tableModelInsumoOrcamento;
    TableRender tableRenderInsumoOrcamento;
    TableRender tableRenderItemOrcamento;
    TableRowSorter tableRowSorterItemOrcamento;
    TableRowSorter tableRowSorterInsumoOrcamento;
    LinkedList<ItemOrcamentoDao> listaItemOrcamento;
    AutoComplete autoCompletarIdentificarItemOrcamento;
    AutoComplete autoCompletarNomeItemOrcamento;
    private TipoItemOrcamento TipoItemComposicao;

    public JanelaOrcamento() {
    }

    /**
     * Creates new form UserWindow
     */
    public JanelaOrcamento(int id) {
        try {
            // Define layout de acordo com o SO que estiver rodando
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            this.setIconImage(JanelaLogin.icon);
            initComponents();
            idOrcamento = id;
            configurarJanela();
            this.setLocationRelativeTo(null);
            this.setVisible(true);
        } catch (Exception e) {
            MensagemExcessao.mostrarMensagem(e, this.getTitle());
        }
    }

    private LinkedList<String> getNomeColunasTabelaItemOrcamento() {
        LinkedList<String> listaNomesColunas = new LinkedList<String>();
        listaNomesColunas.add("");
        listaNomesColunas.add("Item");
        listaNomesColunas.add("Tipo");
        listaNomesColunas.add("Ident.");
        listaNomesColunas.add("Nome");
        listaNomesColunas.add("Unid.");
        listaNomesColunas.add("Quant.");
        listaNomesColunas.add("Valor");
        listaNomesColunas.add("Total");
        return listaNomesColunas;
    }

    private LinkedList<String> getNomeColunasTabelaInsumoOrcamento() {
        LinkedList<String> listaNomesColunas = new LinkedList<String>();
        listaNomesColunas.add("Item");
        listaNomesColunas.add("Tipo");
        listaNomesColunas.add("Ident.");
        listaNomesColunas.add("Nome");
        listaNomesColunas.add("Unid.");
        listaNomesColunas.add("Quant.");
        listaNomesColunas.add("Disp.");
        return listaNomesColunas;
    }

    private void carregarInformacoesItemOrcamento() {
        jButton2.setToolTipText("Editar");
        jButton2.setIcon(new Icons().getEdit());

        jButton4.setEnabled(true);
        jButton3.setEnabled(true);

        ItemOrcamentoDao itemOrcamentoDao = listaItemOrcamento.get(indiceTabelaItemOrcamento);
        if (itemOrcamentoDao.getTipoItemOrcamento() == TipoItemOrcamento.INSUMO) {
            jRadioButton3.setSelected(true);
            jRadioButton1.setSelected(true);
            InsumoDao insumoDao = new InsumoDao();
            insumoDao.buscar(itemOrcamentoDao.getIdInsumo());
            jTextField8.setText(insumoDao.getIdentificador());
            jTextField5.setText(insumoDao.getNome());
            jTextField9.setText(EnumUnidadeInsumo.ConvertEnumString(insumoDao.getUnidadeInsumo()));
        } else {
            jRadioButton4.setSelected(true);
            jRadioButton1.setSelected(true);
            ComposicaoDao composicaoDao = new ComposicaoDao();
            composicaoDao.buscar(itemOrcamentoDao.getIdComposicao());
            jTextField8.setText(composicaoDao.getIdentificador());
            jTextField5.setText(composicaoDao.getNome());
            jTextField9.setText(EnumUnidadeInsumo.ConvertEnumString(composicaoDao.getUnidadeInsumo()));
        }
        jTextField5.requestFocus();

        jTextField10.setText(Format.formatarMonetario(Double.toString(((double) itemOrcamentoDao.getValorUnitario()) / 100)));
        jTextField13.setText(Double.toString(((double) itemOrcamentoDao.getQuantidade()) / 100));

        jScrollPane3.setVisible(false);
        jScrollPane4.setVisible(false);
        autoCompletarIdentificarItemOrcamento.setSearchWord(jTextField8.getText());
        autoCompletarNomeItemOrcamento.setSearchWord(jTextField5.getText());

    }

    private void configurarTabelaItemOrcamento() {
        tableRenderItemOrcamento = new TableRender();
        tableModelItemOrcamento = new TableModel(getNomeColunasTabelaItemOrcamento(), tableRenderItemOrcamento, new InterfaceTable() {
            public void tableAction(int id, int columnIndex, int rowIndex) {
                if (columnIndex < 0) {
                    indiceTabelaItemOrcamento = rowIndex;
                    carregarInformacoesItemOrcamento();
                }
            }

            public boolean isEditableColumn(int columnIndex) {
                if (columnIndex == 0) {
                    return true;
                }
                return false;
            }
        });
        jTable1.setModel(tableModelItemOrcamento);
        jTable1.getColumnModel().getColumn(0).setMaxWidth(30);
        jTable1.getColumnModel().getColumn(0).setMinWidth(30);
        jTable1.getColumnModel().getColumn(0).setResizable(false);
        jTable1.getColumnModel().getColumn(1).setMaxWidth(40);
        jTable1.getColumnModel().getColumn(1).setMinWidth(40);
        jTable1.getColumnModel().getColumn(1).setResizable(false);
        jTable1.getColumnModel().getColumn(2).setMaxWidth(30);
        jTable1.getColumnModel().getColumn(2).setMinWidth(30);
        jTable1.getColumnModel().getColumn(2).setResizable(false);

        jTable1.getColumnModel().getColumn(3).setMaxWidth(50);
        jTable1.getColumnModel().getColumn(3).setMinWidth(50);
        jTable1.getColumnModel().getColumn(3).setResizable(false);

        jTable1.getColumnModel().getColumn(5).setMaxWidth(40);
        jTable1.getColumnModel().getColumn(5).setMinWidth(40);
        jTable1.getColumnModel().getColumn(5).setResizable(false);
        jTable1.getColumnModel().getColumn(6).setMaxWidth(50);
        jTable1.getColumnModel().getColumn(6).setMinWidth(50);
        jTable1.getColumnModel().getColumn(6).setResizable(false);
        jTable1.getColumnModel().getColumn(7).setMaxWidth(60);
        jTable1.getColumnModel().getColumn(7).setMinWidth(60);
        jTable1.getColumnModel().getColumn(7).setResizable(false);
        jTable1.getColumnModel().getColumn(8).setMaxWidth(70);
        jTable1.getColumnModel().getColumn(8).setMinWidth(70);
        jTable1.getColumnModel().getColumn(8).setResizable(false);

        TableRowComparator tableRowComparator = new TableRowComparator();
        tableRowSorterItemOrcamento = tableRowComparator;
        jTable1.setRowSelectionAllowed(false);

        buscarTabelaItemOrcamento();
    }

    private void configurarTabelaInsumoOrcamento() {
        tableRenderInsumoOrcamento = new TableRender();
        tableModelInsumoOrcamento = new TableModel(getNomeColunasTabelaInsumoOrcamento(), tableRenderInsumoOrcamento, new InterfaceTable() {
            public void tableAction(int id, int columnIndex, int rowIndex) {
            }

            public boolean isEditableColumn(int columnIndex) {
                return false;
            }
        });
        jTable2.setModel(tableModelInsumoOrcamento);

        jTable2.getColumnModel().getColumn(0).setMaxWidth(40);
        jTable2.getColumnModel().getColumn(0).setMinWidth(40);
        jTable2.getColumnModel().getColumn(0).setResizable(false);
        jTable2.getColumnModel().getColumn(1).setMaxWidth(40);
        jTable2.getColumnModel().getColumn(1).setMinWidth(40);
        jTable2.getColumnModel().getColumn(1).setResizable(false);
        jTable2.getColumnModel().getColumn(2).setMaxWidth(70);
        jTable2.getColumnModel().getColumn(2).setMinWidth(70);
        jTable2.getColumnModel().getColumn(4).setMaxWidth(40);
        jTable2.getColumnModel().getColumn(4).setMinWidth(40);
        jTable2.getColumnModel().getColumn(4).setResizable(false);
        jTable2.getColumnModel().getColumn(5).setMaxWidth(70);
        jTable2.getColumnModel().getColumn(5).setMinWidth(70);
        jTable2.getColumnModel().getColumn(5).setResizable(false);
        jTable2.getColumnModel().getColumn(6).setMaxWidth(50);
        jTable2.getColumnModel().getColumn(6).setMinWidth(50);
        jTable2.getColumnModel().getColumn(6).setResizable(false);

        TableRowComparator tableRowComparator = new TableRowComparator();
        tableRowSorterInsumoOrcamento = tableRowComparator;
        jTable2.setRowSelectionAllowed(false);
    }

    private void configurarCamposObrigatorios() {
        ((TextFieldValidator) jTextField4).validarCampo();
        configurarCamposItemOrçamento();
    }

    private void configurarCamposItemOrçamento() {
        ((TextFieldValidator) jTextField13).validarCampo();
        if (jRadioButton2.isSelected()) {
            ((TextFieldValidator) jTextField8).validarCampo();
            jLabel8.setForeground(Configurations.getFieldValidationOk());
        } else {
            ((TextFieldValidator) jTextField5).validarCampo();
            jLabel13.setForeground(Configurations.getFieldValidationOk());
        }
    }

    private void limparCamposItens(boolean cancelarEdicao) {
        jTextField8.setText("");
        jTextField5.setText("");
        jTextField9.setText("");
        jTextField13.setText("");
        jTextField10.setText("");
        autoCompletarIdentificarItemOrcamento.setSearchWord("");
        autoCompletarNomeItemOrcamento.setSearchWord("");

        jScrollPane3.setVisible(false);
        configurarCamposItemOrçamento();

        if (cancelarEdicao) {
            jButton2.setToolTipText("Adicionar");
            jButton2.setIcon(new Icons().getAdd());

            jButton3.setEnabled(false);
            jButton4.setEnabled(false);
        }
    }

    private void buscarTabelaItemOrcamento() {
        LinkedList searchResult = new LinkedList();

        LinkedList<Integer> columnId = new LinkedList<Integer>();
        LinkedList<String> colunaNumeroItem = new LinkedList<String>();
        LinkedList<String> colunaTipoItem = new LinkedList<String>();
        LinkedList<String> colunaIdentificador = new LinkedList<String>();
        LinkedList<String> colunaNome = new LinkedList<String>();
        LinkedList<String> colunaUnidade = new LinkedList<String>();
        LinkedList<String> colunaQuantidade = new LinkedList<String>();
        LinkedList<String> colunaValor = new LinkedList<String>();
        LinkedList<String> colunaTotal = new LinkedList<String>();

        for (int i = 0; i < listaItemOrcamento.size(); i++) {
            ItemOrcamentoDao itemOrcamentoDao = listaItemOrcamento.get(i);
            columnId.add(i);
            colunaNumeroItem.add(Integer.toString(i + 1));
            if (itemOrcamentoDao.getTipoItemOrcamento() == TipoItemOrcamento.INSUMO) {
                colunaTipoItem.add("INS");
                InsumoDao insumoDao = new InsumoDao();
                insumoDao.buscar(itemOrcamentoDao.getIdInsumo());
                colunaIdentificador.add(insumoDao.getIdentificador());
                colunaNome.add(insumoDao.getNome());
                colunaUnidade.add(EnumUnidadeInsumo.ConvertEnumString(insumoDao.getUnidadeInsumo()));
            } else {
                colunaTipoItem.add("COM");
                ComposicaoDao composicaoDao = new ComposicaoDao();
                composicaoDao.buscar(itemOrcamentoDao.getIdComposicao());
                colunaIdentificador.add(composicaoDao.getIdentificador());
                colunaNome.add(composicaoDao.getNome());
                colunaUnidade.add(EnumUnidadeInsumo.ConvertEnumString(composicaoDao.getUnidadeInsumo()));
            }
            colunaValor.add(Format.formatarMonetario(Double.toString(((double) itemOrcamentoDao.getValorUnitario()) / 100)));
            colunaQuantidade.add(Double.toString(((double) itemOrcamentoDao.getQuantidade()) / 100));
            colunaTotal.add(Format.formatarMonetario(Double.toString(((double) itemOrcamentoDao.getValorUnitario() * itemOrcamentoDao.getQuantidade()) / 10000)));

        }

        if (listaItemOrcamento.size() > 0) {
            searchResult.add(columnId);
            searchResult.add(Format.getBooleanLinkedList(columnId.size()));
            searchResult.add(colunaNumeroItem);
            searchResult.add(colunaTipoItem);
            searchResult.add(colunaIdentificador);
            searchResult.add(colunaNome);
            searchResult.add(colunaUnidade);
            searchResult.add(colunaQuantidade);
            searchResult.add(colunaValor);
            searchResult.add(colunaTotal);
        }

        tableModelItemOrcamento.update(searchResult);
        jTable1.setDefaultRenderer(Object.class, tableRenderItemOrcamento);
        tableRowSorterItemOrcamento.setModel(tableModelItemOrcamento);

        jTable1.setRowSorter(tableRowSorterItemOrcamento);
    }

    private void buscarTabelaInsumoOrcamento() {
        LinkedList searchResult = new LinkedList();

        LinkedList<Integer> columnId = new LinkedList<Integer>();
        LinkedList<String> colunaNumeroItem = new LinkedList<String>();
        LinkedList<String> colunaTipoItem = new LinkedList<String>();
        LinkedList<String> colunaIdentificador = new LinkedList<String>();
        LinkedList<String> colunaNome = new LinkedList<String>();
        LinkedList<String> colunaUnidade = new LinkedList<String>();
        LinkedList<String> colunaQuantidade = new LinkedList<String>();
        LinkedList<String> colunaDisponivel = new LinkedList<String>();

        LinkedList<InsumoOrcamentoDao> listaInsumoOrcamento = InsumoOrcamentoDao.listarInsumoOrcamentoResumida(idOrcamento);

        for (int i = 0; i < listaInsumoOrcamento.size(); i++) {
            InsumoOrcamentoDao insumoOrcamentoDao = listaInsumoOrcamento.get(i);
            columnId.add(i);
            colunaNumeroItem.add(Integer.toString(i + 1));
            colunaTipoItem.add(EnumTipoInsumo.ConvertEnumString(insumoOrcamentoDao.getTipoInsumo()));
            colunaIdentificador.add(insumoOrcamentoDao.getIdentificador());
            colunaNome.add(insumoOrcamentoDao.getNome());
            colunaUnidade.add(EnumUnidadeInsumo.ConvertEnumString(insumoOrcamentoDao.getUnidadeInsumo()));
            colunaQuantidade.add(Double.toString(((double) insumoOrcamentoDao.getQuantidade()) / 100));

            InsumoDao insumoDao = new InsumoDao();
            insumoDao.buscar(insumoOrcamentoDao.getIdInsumo());

            colunaDisponivel.add(Double.toString(((double) insumoDao.getQuantidade()) / 100));
        }

        if (listaItemOrcamento.size() > 0) {
            searchResult.add(columnId);
            searchResult.add(colunaNumeroItem);
            searchResult.add(colunaTipoItem);
            searchResult.add(colunaIdentificador);
            searchResult.add(colunaNome);
            searchResult.add(colunaUnidade);
            searchResult.add(colunaQuantidade);
            searchResult.add(colunaDisponivel);
        }

        tableModelInsumoOrcamento.update(searchResult);
        jTable2.setDefaultRenderer(Object.class, tableRenderInsumoOrcamento);
        tableRowSorterInsumoOrcamento.setModel(tableModelInsumoOrcamento);

        jTable2.setRowSorter(tableRowSorterInsumoOrcamento);
    }

    private LinkedList<String> validarCamposEntradaEstoque() {
        LinkedList<String> fieldList = new LinkedList<String>();
        if (!((TextFieldValidator) jTextField4).validarCampo()) {// Documento
            fieldList.add(((TextFieldValidator) jTextField4).getjLabel().getText());
        }
        if (listaItemOrcamento.size() == 0) {
            fieldList.add("Lista de itens vazia.");
        }
        return fieldList;
    }

    private LinkedList<String> valirdarCamposItemOrcamento() {
        LinkedList<String> fieldList = new LinkedList<String>();
        if (jRadioButton2.isSelected()) {
            if (!((TextFieldValidator) jTextField8).validarCampo()) {// Identificador
                fieldList.add(((TextFieldValidator) jTextField8).getjLabel().getText());
            }
        } else {
            if (!((TextFieldValidator) jTextField5).validarCampo()) {// Nome
                fieldList.add(((TextFieldValidator) jTextField5).getjLabel().getText());
            }
        }
        if (!((TextFieldValidator) jTextField13).validarCampo()) {// Quantidade
            fieldList.add(((TextFieldValidator) jTextField13).getjLabel().getText());
        }
        return fieldList;
    }

    private void adicionarOrcamento() {
        try {
            try {
                if (listaItemOrcamento.size() > 0) {
                    if (OrcamentoDao.getIdOrcamentoPorIdentificador(jTextField4.getText()) == 0) {
                        JanelaLogin.connection.setAutoCommit(false);

                        OrcamentoDao orcamentoDao = new OrcamentoDao();
                        orcamentoDao.setIdentificador(jTextField4.getText());
                        orcamentoDao.setIdClienteFornecedor(ClienteFornecedorDao.getIdClienteFornecedorPorIdentificador(jComboBox1.getSelectedItem().toString()));
                        orcamentoDao.setDtOrcamento(Format.getCurrentDatabseTimeStamp());
                        orcamentoDao.setObjeto(jTextArea2.getText());
                        orcamentoDao.setValorCalculado(this.calcularTotalOrcamento());

                        orcamentoDao.inserir();
                        idOrcamento = orcamentoDao.getId();

                        for (int i = 0; i < listaItemOrcamento.size(); i++) {
                            ItemOrcamentoDao itemOrcamentoDao = listaItemOrcamento.get(i);
                            itemOrcamentoDao.setIdOrcamento(idOrcamento);
                            itemOrcamentoDao.inserir();
                        }

                        JanelaLogin.connection.commit();

                        JOptionPane.showMessageDialog(null, "Orçamento cadastrado com sucesso.", this.getTitle(), JOptionPane.INFORMATION_MESSAGE);

                        jTextField7.setText(Format.formatarMonetario(Double.toString(((double) this.calcularTotalOrcamento()) / 100)));
                        jButton1.setText("Editar");
                        jButton1.setIcon(new Icons().getEdit());

                    } else {
                        JOptionPane.showMessageDialog(null, "Este orçamento já esta cadastrada.", this.getTitle(), JOptionPane.ERROR_MESSAGE);
                    }
                } else {
                    JOptionPane.showMessageDialog(null, "Adicione pelo menos um item ao orçamento.", this.getTitle(), JOptionPane.ERROR_MESSAGE);
                }
            } catch (Exception e) {
                JanelaLogin.connection.rollback();
                MensagemExcessao.mostrarMensagem(e, this.getTitle());
            } finally {
                JanelaLogin.connection.setAutoCommit(true);
            }
        } catch (Exception ex) {
            MensagemExcessao.mostrarMensagem(ex, this.getTitle());
        }
    }

    private void editarComposicao() {
        try {
            try {
                if (listaItemOrcamento.size() > 0) {
                    int idOrcamentoBuscado = OrcamentoDao.getIdOrcamentoPorIdentificador(jTextField4.getText());
                    if (idOrcamentoBuscado == 0 || idOrcamentoBuscado == idOrcamento) {
                        JanelaLogin.connection.setAutoCommit(false);

                        OrcamentoDao orcamentoDao = new OrcamentoDao();
                        orcamentoDao.buscar(idOrcamento);
                        orcamentoDao.setIdentificador(jTextField4.getText());
                        orcamentoDao.setIdClienteFornecedor(ClienteFornecedorDao.getIdClienteFornecedorPorIdentificador(jComboBox1.getSelectedItem().toString()));
                        orcamentoDao.setObjeto(jTextArea2.getText());
                        orcamentoDao.setValorCalculado(this.calcularTotalOrcamento());

                        orcamentoDao.atualizar();

                        ItemOrcamentoDao itemOrcamentoDao = new ItemOrcamentoDao();
                        itemOrcamentoDao.setIdOrcamento(idOrcamento);
                        itemOrcamentoDao.deletar();

                        for (int i = 0; i < listaItemOrcamento.size(); i++) {
                            itemOrcamentoDao = listaItemOrcamento.get(i);
                            itemOrcamentoDao.setIdOrcamento(idOrcamento);
                            itemOrcamentoDao.inserir();
                        }

                        JanelaLogin.connection.commit();

                        JOptionPane.showMessageDialog(null, "Orçamento editado com sucesso.", this.getTitle(), JOptionPane.INFORMATION_MESSAGE);

                    } else {
                        JOptionPane.showMessageDialog(null, "Este orçamento já esta cadastrada.", this.getTitle(), JOptionPane.ERROR_MESSAGE);
                    }
                } else {
                    JOptionPane.showMessageDialog(null, "Adicione pelo menos um item ao orçamento.", this.getTitle(), JOptionPane.ERROR_MESSAGE);
                }
            } catch (Exception e) {
                JanelaLogin.connection.rollback();
                MensagemExcessao.mostrarMensagem(e, this.getTitle());
            } finally {
                JanelaLogin.connection.setAutoCommit(true);
            }
        } catch (Exception ex) {
            MensagemExcessao.mostrarMensagem(ex, this.getTitle());
        }
    }

    private void adicionarItemOrcamento() {
        try {
            int idBuscado = jRadioButton3.isSelected() ? InsumoDao.getIdInsumoPorIdentificador(jTextField8.getText()) : ComposicaoDao.getIdComposicaoPorIdentificador(jTextField8.getText());
            if (idBuscado != 0) {
                ItemOrcamentoDao itemOrcamentoDao = new ItemOrcamentoDao();
                if (jRadioButton3.isSelected()) {//Insumo
                    itemOrcamentoDao.setTipoItemOrcamento(TipoItemOrcamento.INSUMO);
                    itemOrcamentoDao.setIdInsumo(idBuscado);
                    InsumoDao insumoDao = new InsumoDao();
                    insumoDao.buscar(idBuscado);
                    itemOrcamentoDao.setValorUnitario(insumoDao.getValorUnitario());
                } else {
                    itemOrcamentoDao.setTipoItemOrcamento(TipoItemOrcamento.COMPOSICAO);
                    itemOrcamentoDao.setIdComposicao(idBuscado);
                    ComposicaoDao composicaoDao = new ComposicaoDao();
                    composicaoDao.buscar(idBuscado);
                    itemOrcamentoDao.setValorUnitario(composicaoDao.getValorUnitario());
                }
                itemOrcamentoDao.setQuantidade((int) (Format.formatarStringDouble(jTextField13.getText()) * 100));
                if (!jButton4.isEnabled()) {
                    listaItemOrcamento.add(itemOrcamentoDao);
                } else {
                    listaItemOrcamento.set(indiceTabelaItemOrcamento, itemOrcamentoDao);
                }
                limparCamposItens(true);

                buscarTabelaItemOrcamento();

            } else {
                JOptionPane.showMessageDialog(null, "Insumo/Composição não encontrada.", this.getTitle(), JOptionPane.ERROR_MESSAGE);
            }

        } catch (Exception ex) {
            MensagemExcessao.mostrarMensagem(ex, this.getTitle());
        }
    }

    private void carregarInformacoes() {
        jButton1.setText("Editar");
        jButton1.setIcon(new Icons().getEdit());

        OrcamentoDao orcamentoDao = new OrcamentoDao();
        orcamentoDao.buscar(idOrcamento);

        jTextField4.setText(orcamentoDao.getIdentificador());
        jTextArea2.setText(orcamentoDao.getObjeto());
        jFormattedTextField1.setText(Format.formatarTimeStampApresentacao(orcamentoDao.getDtOrcamento()));

        ClienteFornecedorDao clienteFornecedorDao = new ClienteFornecedorDao();
        clienteFornecedorDao.buscar(orcamentoDao.getIdClienteFornecedor());

        jComboBox1.setSelectedItem(clienteFornecedorDao.getIdentificador());

        listaItemOrcamento = ItemOrcamentoDao.listarItemOrcamentoPorOrcemento(idOrcamento);

        jTextField7.setText(Format.formatarMonetario(Double.toString(((double) this.calcularTotalOrcamento()) / 100)));

        buscarTabelaItemOrcamento();
    }

    /**
     * Inicializando as configurações da tela
     *
     * @throws SQLException
     */
    private void configurarJanela() throws SQLException {
        autoCompletarIdentificarItemOrcamento = new AutoComplete(jList2, jScrollPane3, jTextField8);
        autoCompletarNomeItemOrcamento = new AutoComplete(jList4, jScrollPane4, jTextField5);

        listaItemOrcamento = new LinkedList<ItemOrcamentoDao>();

        configurarTabelaItemOrcamento();

        LinkedList<String> listaClientesForncedores = ClienteFornecedorDao.getListaIdentificadorClienteFornecedor();
        for (int i = 0; i < listaClientesForncedores.size(); i++) {
            jComboBox1.addItem(listaClientesForncedores.get(i).toString());
        }

        if (idOrcamento != 0) {
            carregarInformacoes();
        } else {
            configurarCamposObrigatorios();
        }

        configurarTabelaInsumoOrcamento();

    }

    private void selecionarItemOrcamento(int idItemBuscado) {
        if (idItemBuscado == 0) {
            idItemBuscado = (jRadioButton3.isSelected()) ? InsumoDao.getIdInsumoPorIdentificador(jTextField8.getText()) : ComposicaoDao.getIdComposicaoPorIdentificador(jTextField8.getText());
            if (idItemBuscado == 0) {
                idItemBuscado = (jRadioButton3.isSelected()) ? InsumoDao.getIdInsumoPorNome(jTextField5.getText()) : ComposicaoDao.getIdComposicaoPorNome(jTextField5.getText());
            }
        }

        if (jRadioButton3.isSelected()) { // INSUMO
            InsumoDao insumoDao = new InsumoDao();
            insumoDao.buscar(idItemBuscado);
            jTextField8.setText(insumoDao.getIdentificador());
            jTextField5.setText(insumoDao.getNome());
            jTextField9.setText(EnumUnidadeInsumo.ConvertEnumString(insumoDao.getUnidadeInsumo()));

            jTextField10.setText(Format.formatarMonetario(Double.toString(((double) insumoDao.getValorUnitario()) / 100)));
        } else {
            ComposicaoDao composicaoDao = new ComposicaoDao();
            composicaoDao.buscar(idItemBuscado);
            jTextField8.setText(composicaoDao.getIdentificador());
            jTextField5.setText(composicaoDao.getNome());
            jTextField9.setText(EnumUnidadeInsumo.ConvertEnumString(composicaoDao.getUnidadeInsumo()));

            jTextField10.setText(Format.formatarMonetario(Double.toString(((double) composicaoDao.getValorUnitario()) / 100)));
        }

    }

    public void modificarOpcaoAutocompletar(boolean opcao) {
        jTextField8.setEnabled(opcao);
        jTextField5.setEnabled(!opcao);
        jScrollPane3.setVisible(false);
        jScrollPane4.setVisible(false);
        limparCamposItens(false);
    }

    public void imprimir(int id) {
        try {
            HashMap parameters = new HashMap();

            parameters.put("idSaidaEstoque", id);
            InputStream is = this.getClass().getClassLoader().getResourceAsStream("manager/modulo/estoque/relatorio/SaidaEstoque.jasper");
            Connection connection = JanelaLogin.getConnection();
            JasperPrint relat = JasperFillManager.fillReport(is, parameters, connection);
            JasperViewer.viewReport(relat, false);
        } catch (Exception e) {
            MensagemExcessao.mostrarMensagem(e, "Saida do Estoque");
        }

    }

    private int calcularTotalOrcamento() {
        int total = 0;
        for (int i = 0; i < listaItemOrcamento.size(); i++) {
            ItemOrcamentoDao itemOrcamentoDao = listaItemOrcamento.get(i);
            total += (itemOrcamentoDao.getValorUnitario() * itemOrcamentoDao.getQuantidade()) / 100;
        }
        return total;
    }

    public void inserirInsumoOrcamento(int idInsumo, int quantidade, int valorUnitario) throws SQLException {
        InsumoDao insumoDao = new InsumoDao();
        insumoDao.buscar(idInsumo);

        InsumoOrcamentoDao insumoOrcamentoDao = new InsumoOrcamentoDao();
        insumoOrcamentoDao.setIdOrcamento(idOrcamento);
        insumoOrcamentoDao.setIdentificador(insumoDao.getIdentificador());
        insumoOrcamentoDao.setNome(insumoDao.getNome());
        insumoOrcamentoDao.setTipoInsumo(insumoDao.getTipoInsumo());
        insumoOrcamentoDao.setQuantidade(quantidade);
        insumoOrcamentoDao.setUnidadeInsumo(insumoDao.getUnidadeInsumo());
        insumoOrcamentoDao.setValorUnitario(valorUnitario);
        insumoOrcamentoDao.setIdInsumo(insumoDao.getId());
        insumoOrcamentoDao.inserir();
    }

    public void inserirComposicaoOrcamento(int idComposicao, int quantidade, int valorUnitario) throws SQLException {
        LinkedList<ItemComposicaoDao> listaItemComposicao = ItemComposicaoDao.listarItemPorComposicaoPai(idComposicao);

        for (int j = 0; j < listaItemComposicao.size(); j++) {
            ItemComposicaoDao itemComposicaoDao = listaItemComposicao.get(j);

            if (itemComposicaoDao.getTipoItem() == TipoItemOrcamento.COMPOSICAO) {
                inserirComposicaoOrcamento(itemComposicaoDao.getIdComposicao(), quantidade, itemComposicaoDao.getValorUnitario());
            } else {
                inserirInsumoOrcamento(itemComposicaoDao.getIdInsumo(), (quantidade * itemComposicaoDao.getQuantidade()) / 100, itemComposicaoDao.getValorUnitario());
            }
        }
    }

    private void gerarListaInsumos() {
        try {
            try {
                JanelaLogin.connection.setAutoCommit(false);
                LinkedList<ItemOrcamentoDao> listaItemOrcamentoBuscada = ItemOrcamentoDao.listarItemOrcamentoPorOrcemento(idOrcamento);
                InsumoOrcamentoDao insumoOrcamentoDao = new InsumoOrcamentoDao();
                insumoOrcamentoDao.setIdOrcamento(idOrcamento);
                insumoOrcamentoDao.deletar();
                for (int i = 0; i < listaItemOrcamentoBuscada.size(); i++) {
                    ItemOrcamentoDao itemOrcamentoDao = listaItemOrcamentoBuscada.get(i);

                    if (itemOrcamentoDao.getTipoItemOrcamento() == TipoItemOrcamento.INSUMO) {
                        inserirInsumoOrcamento(itemOrcamentoDao.getIdInsumo(), itemOrcamentoDao.getQuantidade(), itemOrcamentoDao.getValorUnitario());
                    } else {
                        inserirComposicaoOrcamento(itemOrcamentoDao.getIdComposicao(), itemOrcamentoDao.getQuantidade(), itemOrcamentoDao.getValorUnitario());
                    }
                }
                JOptionPane.showMessageDialog(null, "Lista de Insumos gerada com sucesso.", this.getTitle(), JOptionPane.INFORMATION_MESSAGE);
                JanelaLogin.connection.commit();

                buscarTabelaInsumoOrcamento();
            } catch (Exception e) {
                JanelaLogin.connection.rollback();
                MensagemExcessao.mostrarMensagem(e, this.getTitle());
            } finally {
                JanelaLogin.connection.setAutoCommit(true);
            }
        } catch (Exception ex) {
            MensagemExcessao.mostrarMensagem(ex, this.getTitle());
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        buttonGroup2 = new javax.swing.ButtonGroup();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel3 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jLabel13 = new javax.swing.JLabel();
        jTextField8 = new TextFieldValidator(-1, -1, true, true, "text", jLabel13);
        jScrollPane3 = new javax.swing.JScrollPane();
        jList2 = new javax.swing.JList();
        jButton4 = new javax.swing.JButton();
        jLabel8 = new javax.swing.JLabel();
        jTextField5 = new TextFieldValidator(-1, -1, true, true, "text", jLabel8);
        jScrollPane4 = new javax.swing.JScrollPane();
        jList4 = new javax.swing.JList();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel11 = new javax.swing.JLabel();
        jTextField9 = new javax.swing.JTextField();
        jLabel12 = new javax.swing.JLabel();
        jTextField13 = new TextFieldValidator(10, 1, true, true, "double", jLabel11);
        jRadioButton3 = new javax.swing.JRadioButton();
        jRadioButton4 = new javax.swing.JRadioButton();
        jRadioButton1 = new javax.swing.JRadioButton();
        jRadioButton2 = new javax.swing.JRadioButton();
        jLabel14 = new javax.swing.JLabel();
        jTextField10 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        jTextField4 = new TextFieldValidator(12, -1, true, true, "text", jLabel7);
        jLabel44 = new javax.swing.JLabel();
        jScrollPane5 = new javax.swing.JScrollPane();
        jTextArea2 = new javax.swing.JTextArea();
        jLabel10 = new javax.swing.JLabel();
        jTextField7 = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jFormattedTextField1 = new FormatedFieldValidator(true, true, "date", jLabel6);
        jLabel2 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jButton5 = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        jPanel5 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        jPanel6 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        jButton7 = new javax.swing.JButton();
        jButton8 = new javax.swing.JButton();
        jLabel9 = new javax.swing.JLabel();
        jLabel15 = new javax.swing.JLabel();
        jButton9 = new javax.swing.JButton();
        jButton10 = new javax.swing.JButton();
        jPanel7 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("ORÇAMENTO");
        setBackground(Configurations.getBackGroundColor());
        setMinimumSize(new java.awt.Dimension(770, 670));
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });
        getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.LINE_AXIS));

        jTabbedPane1.setBackground(Configurations.getBackGroundColor());

        jPanel3.setBackground(Configurations.getBackGroundColor());
        jPanel3.setPreferredSize(new java.awt.Dimension(700, 320));
        jPanel3.setLayout(null);

        jPanel1.setBackground(Configurations.getBackGroundColor());
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jPanel1.setLayout(null);

        jPanel2.setBackground(Configurations.getBackGroundColor());
        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("LISTA DE INSUMOS"));
        jPanel2.setLayout(null);

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/add.png"))); // NOI18N
        jButton2.setToolTipText("Adicionar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton2);
        jButton2.setBounds(650, 50, 30, 30);

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/cancel.png"))); // NOI18N
        jButton3.setToolTipText("Cancelar");
        jButton3.setEnabled(false);
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton3);
        jButton3.setBounds(690, 70, 30, 30);

        jLabel13.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel13.setText("Identificador");
        jPanel2.add(jLabel13);
        jLabel13.setBounds(35, 40, 90, 14);

        jTextField8.setDisabledTextColor(new java.awt.Color(51, 51, 51));
        jTextField8.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextField8KeyReleased(evt);
            }
        });
        jPanel2.add(jTextField8);
        jTextField8.setBounds(10, 60, 120, 20);

        jScrollPane3.setVisible(false);

        jList2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jList2MouseReleased(evt);
            }
        });
        jList2.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jList2KeyReleased(evt);
            }
        });
        jScrollPane3.setViewportView(jList2);

        jPanel2.add(jScrollPane3);
        jScrollPane3.setBounds(10, 80, 120, 50);

        jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/remove.png"))); // NOI18N
        jButton4.setToolTipText("Remover");
        jButton4.setEnabled(false);
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton4);
        jButton4.setBounds(690, 30, 30, 30);

        jLabel8.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel8.setText("Nome");
        jPanel2.add(jLabel8);
        jLabel8.setBounds(155, 40, 110, 14);

        jTextField5.setDisabledTextColor(new java.awt.Color(51, 51, 51));
        jTextField5.setEnabled(false);
        jTextField5.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextField5KeyReleased(evt);
            }
        });
        jPanel2.add(jTextField5);
        jTextField5.setBounds(135, 60, 300, 20);

        jScrollPane4.setVisible(false);

        jList4.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jList4MouseReleased(evt);
            }
        });
        jList4.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jList4KeyReleased(evt);
            }
        });
        jScrollPane4.setViewportView(jList4);

        jPanel2.add(jScrollPane4);
        jScrollPane4.setBounds(135, 80, 300, 50);

        jScrollPane1.setViewportView(jTable1);

        jPanel2.add(jScrollPane1);
        jScrollPane1.setBounds(10, 100, 720, 320);

        jLabel11.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel11.setText("Quantidade");
        jPanel2.add(jLabel11);
        jLabel11.setBounds(570, 40, 70, 14);

        jTextField9.setDisabledTextColor(new java.awt.Color(51, 51, 51));
        jTextField9.setEnabled(false);
        jPanel2.add(jTextField9);
        jTextField9.setBounds(440, 60, 40, 20);

        jLabel12.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel12.setText("Unid.");
        jPanel2.add(jLabel12);
        jLabel12.setBounds(440, 40, 40, 14);

        jTextField13.setDisabledTextColor(new java.awt.Color(51, 51, 51));
        jPanel2.add(jTextField13);
        jTextField13.setBounds(570, 60, 70, 20);

        jRadioButton3.setBackground(Configurations.getBackGroundColor());
        buttonGroup2.add(jRadioButton3);
        jRadioButton3.setSelected(true);
        jRadioButton3.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jRadioButton3ItemStateChanged(evt);
            }
        });
        jPanel2.add(jRadioButton3);
        jRadioButton3.setBounds(30, 20, 20, 15);

        jRadioButton4.setBackground(Configurations.getBackGroundColor());
        buttonGroup2.add(jRadioButton4);
        jPanel2.add(jRadioButton4);
        jRadioButton4.setBounds(100, 20, 20, 15);

        jRadioButton1.setBackground(Configurations.getBackGroundColor());
        buttonGroup1.add(jRadioButton1);
        jPanel2.add(jRadioButton1);
        jRadioButton1.setBounds(130, 35, 21, 21);

        jRadioButton2.setBackground(Configurations.getBackGroundColor());
        buttonGroup1.add(jRadioButton2);
        jRadioButton2.setSelected(true);
        jRadioButton2.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jRadioButton2ItemStateChanged(evt);
            }
        });
        jPanel2.add(jRadioButton2);
        jRadioButton2.setBounds(10, 35, 21, 21);

        jLabel14.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel14.setText("Valor");
        jPanel2.add(jLabel14);
        jLabel14.setBounds(485, 40, 60, 14);

        jTextField10.setDisabledTextColor(new java.awt.Color(51, 51, 51));
        jTextField10.setEnabled(false);
        jPanel2.add(jTextField10);
        jTextField10.setBounds(485, 60, 80, 20);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel1.setText("Insumo");
        jPanel2.add(jLabel1);
        jLabel1.setBounds(50, 20, 50, 14);

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel3.setText("Composição");
        jPanel2.add(jLabel3);
        jLabel3.setBounds(120, 20, 80, 14);

        jPanel1.add(jPanel2);
        jPanel2.setBounds(15, 140, 740, 430);

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/add.png"))); // NOI18N
        jButton1.setText("Cadastrar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton1);
        jButton1.setBounds(10, 570, 100, 23);

        jButton6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/cancel.png"))); // NOI18N
        jButton6.setText("Cancelar");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton6);
        jButton6.setBounds(130, 570, 100, 23);

        jLabel7.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel7.setText("Identificador");
        jPanel1.add(jLabel7);
        jLabel7.setBounds(20, 10, 80, 14);

        jTextField4.setDisabledTextColor(new java.awt.Color(51, 51, 51));
        jPanel1.add(jTextField4);
        jTextField4.setBounds(20, 30, 110, 20);

        jLabel44.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel44.setText("Objeto");
        jPanel1.add(jLabel44);
        jLabel44.setBounds(20, 60, 80, 14);

        jTextArea2.setColumns(20);
        jTextArea2.setFont(new java.awt.Font("Monospaced", 1, 10)); // NOI18N
        jTextArea2.setLineWrap(true);
        jTextArea2.setRows(2);
        jTextArea2.setWrapStyleWord(true);
        jScrollPane5.setViewportView(jTextArea2);
        jTextArea2.setDocument(new FixedLengthDocument(150));

        jPanel1.add(jScrollPane5);
        jScrollPane5.setBounds(20, 80, 730, 50);

        jLabel10.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel10.setText("Valor Calculado");
        jPanel1.add(jLabel10);
        jLabel10.setBounds(600, 10, 110, 14);

        jTextField7.setDisabledTextColor(new java.awt.Color(51, 51, 51));
        jTextField7.setEnabled(false);
        jPanel1.add(jTextField7);
        jTextField7.setBounds(600, 30, 110, 20);

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel6.setText("Data de Cadastro");
        jPanel1.add(jLabel6);
        jLabel6.setBounds(135, 10, 110, 14);

        jFormattedTextField1.setDisabledTextColor(new java.awt.Color(51, 51, 51));
        jFormattedTextField1.setEnabled(false);
        jPanel1.add(jFormattedTextField1);
        jFormattedTextField1.setBounds(135, 30, 100, 20);

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel2.setText("Cliente/Fornecedor");
        jPanel1.add(jLabel2);
        jLabel2.setBounds(240, 10, 150, 14);

        jPanel1.add(jComboBox1);
        jComboBox1.setBounds(240, 30, 355, 20);

        jButton5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/refresh.png"))); // NOI18N
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton5);
        jButton5.setBounds(720, 20, 30, 30);

        jPanel3.add(jPanel1);
        jPanel1.setBounds(0, 0, 760, 610);

        jTabbedPane1.addTab("Orçamento", jPanel3);

        jPanel4.setBackground(Configurations.getBackGroundColor());
        jPanel4.setLayout(null);

        jPanel5.setBackground(Configurations.getBackGroundColor());
        jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jPanel5.setLayout(null);
        jPanel5.add(jLabel5);
        jLabel5.setBounds(170, 10, 0, 0);

        jPanel6.setBackground(Configurations.getBackGroundColor());
        jPanel6.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jPanel6.setLayout(null);

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel4.setText("Lista de Insumos :");
        jPanel6.add(jLabel4);
        jLabel4.setBounds(10, 20, 120, 14);

        jButton7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/table.png"))); // NOI18N
        jButton7.setText("Gerar");
        jButton7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton7ActionPerformed(evt);
            }
        });
        jPanel6.add(jButton7);
        jButton7.setBounds(130, 20, 90, 23);

        jButton8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/refresh.png"))); // NOI18N
        jButton8.setText("Atualizar");
        jButton8.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton8ActionPerformed(evt);
            }
        });
        jPanel6.add(jButton8);
        jButton8.setBounds(370, 20, 110, 23);

        jLabel9.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel9.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel9.setText("Exportar Tabela:");
        jPanel6.add(jLabel9);
        jLabel9.setBounds(500, 20, 110, 14);

        jLabel15.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel15.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel15.setText("Tabela de Insumos:");
        jPanel6.add(jLabel15);
        jLabel15.setBounds(250, 20, 110, 14);

        jButton9.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/pdf.png"))); // NOI18N
        jButton9.setText("PDF");
        jButton9.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton9ActionPerformed(evt);
            }
        });
        jPanel6.add(jButton9);
        jButton9.setBounds(640, 30, 90, 23);

        jButton10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/excel.png"))); // NOI18N
        jButton10.setText("Excel");
        jButton10.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton10ActionPerformed(evt);
            }
        });
        jPanel6.add(jButton10);
        jButton10.setBounds(640, 5, 90, 23);

        jPanel5.add(jPanel6);
        jPanel6.setBounds(0, 0, 760, 60);

        jPanel7.setBackground(Configurations.getBackGroundColor());
        jPanel7.setLayout(new java.awt.GridLayout(1, 0));

        jScrollPane2.setViewportView(jTable2);

        jPanel7.add(jScrollPane2);

        jPanel5.add(jPanel7);
        jPanel7.setBounds(0, 60, 760, 550);

        jPanel4.add(jPanel5);
        jPanel5.setBounds(0, 0, 760, 610);

        jTabbedPane1.addTab("Lista de Insumos", jPanel4);

        getContentPane().add(jTabbedPane1);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
        WindowsFunctions.resizePanel(jPanel3, jPanel1);
        WindowsFunctions.resizePanel(jPanel4, jPanel5);
    }//GEN-LAST:event_formComponentResized

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        LinkedList<String> fieldValidadeList = validarCamposEntradaEstoque();
        if (fieldValidadeList.size() == 0) {
            if (idOrcamento == 0) {
                adicionarOrcamento();
            } else {
                editarComposicao();
            }
        } else {
            JOptionPane.showMessageDialog(null, ValidationFunctions.getValidationMessage(fieldValidadeList), this.getTitle(), JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        this.dispose();
    }//GEN-LAST:event_jButton6ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        LinkedList<String> fieldValidadeList = valirdarCamposItemOrcamento();
        if (fieldValidadeList.size() == 0) {
            adicionarItemOrcamento();
        } else {
            JOptionPane.showMessageDialog(null, ValidationFunctions.getValidationMessage(fieldValidadeList), this.getTitle(), JOptionPane.ERROR_MESSAGE);
        }
}//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        limparCamposItens(true);
}//GEN-LAST:event_jButton3ActionPerformed

    private void jTextField8KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField8KeyReleased
        try {
            if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
                selecionarItemOrcamento(0);
            } else if (evt.getKeyCode() == KeyEvent.VK_DOWN) {
                if (autoCompletarIdentificarItemOrcamento.getjScrollPane().isVisible()) {
                    autoCompletarIdentificarItemOrcamento.getjList().setSelectedIndex(0);
                    autoCompletarIdentificarItemOrcamento.getjList().requestFocus();
                }
            } else {
                if (!autoCompletarIdentificarItemOrcamento.getSearchWord().equals(jTextField8.getText())) {
                    autoCompletarIdentificarItemOrcamento.setSearchWord(jTextField8.getText());
                    String opcao = (jRadioButton3.isSelected() ? "Identificador Insumo" : "Identificador Composicao");
                    autoCompletarIdentificarItemOrcamento.update(new ItemOrcamentoDao().buscar(opcao, jTextField8.getText(), true));
                }
            }
        } catch (Exception e) {
            MensagemExcessao.mostrarMensagem(e, this.getTitle());
        }
    }//GEN-LAST:event_jTextField8KeyReleased

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        listaItemOrcamento.remove(indiceTabelaItemOrcamento);
        limparCamposItens(true);
        buscarTabelaItemOrcamento();
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jList2KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jList2KeyReleased
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            autoCompletarIdentificarItemOrcamento.setSearchWord(autoCompletarIdentificarItemOrcamento.getjList().getSelectedValue().toString());
            autoCompletarIdentificarItemOrcamento.getjScrollPane().setVisible(false);
            selecionarItemOrcamento(0);
        }
    }//GEN-LAST:event_jList2KeyReleased

    private void jList2MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList2MouseReleased
        autoCompletarIdentificarItemOrcamento.setSearchWord(autoCompletarIdentificarItemOrcamento.getjList().getSelectedValue().toString());
        autoCompletarIdentificarItemOrcamento.getjScrollPane().setVisible(false);
        selecionarItemOrcamento(0);
    }//GEN-LAST:event_jList2MouseReleased

    private void jList4MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList4MouseReleased
        autoCompletarNomeItemOrcamento.setSearchWord(autoCompletarNomeItemOrcamento.getjList().getSelectedValue().toString());
        autoCompletarNomeItemOrcamento.getjScrollPane().setVisible(false);
        selecionarItemOrcamento(0);
    }//GEN-LAST:event_jList4MouseReleased

    private void jList4KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jList4KeyReleased
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            autoCompletarNomeItemOrcamento.setSearchWord(autoCompletarNomeItemOrcamento.getjList().getSelectedValue().toString());
            autoCompletarNomeItemOrcamento.getjScrollPane().setVisible(false);
            selecionarItemOrcamento(0);
        }
    }//GEN-LAST:event_jList4KeyReleased

    private void jRadioButton2ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jRadioButton2ItemStateChanged
        modificarOpcaoAutocompletar(jRadioButton2.isSelected());
    }//GEN-LAST:event_jRadioButton2ItemStateChanged

    private void jTextField5KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField5KeyReleased
        try {
            if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
                selecionarItemOrcamento(0);
            } else if (evt.getKeyCode() == KeyEvent.VK_DOWN) {
                if (autoCompletarNomeItemOrcamento.getjScrollPane().isVisible()) {
                    autoCompletarNomeItemOrcamento.getjList().setSelectedIndex(0);
                    autoCompletarNomeItemOrcamento.getjList().requestFocus();
                }
            } else {
                if (!autoCompletarNomeItemOrcamento.getSearchWord().equals(jTextField5.getText())) {
                    autoCompletarNomeItemOrcamento.setSearchWord(jTextField5.getText());
                    String opcao = (jRadioButton3.isSelected() ? "Nome Insumo" : "Nome Composicao");
                    autoCompletarNomeItemOrcamento.update(new ItemOrcamentoDao().buscar(opcao, jTextField5.getText(), true));
                }
            }
        } catch (Exception e) {
            MensagemExcessao.mostrarMensagem(e, this.getTitle());
        }
    }//GEN-LAST:event_jTextField5KeyReleased

    private void jRadioButton3ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jRadioButton3ItemStateChanged
        limparCamposItens(false);
    }//GEN-LAST:event_jRadioButton3ItemStateChanged

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        int total = this.calcularTotalOrcamento();

        jTextField7.setText(Format.formatarMonetario(Double.toString(((double) total) / 100)));
    }//GEN-LAST:event_jButton5ActionPerformed

    private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
        Object[] options = {"Sim", "Não"};
        int j = JOptionPane.showOptionDialog(null, "Tem certeza que deseja gerar novamente a lista de insumos?", "Orçamento", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
        if (j == JOptionPane.YES_OPTION) {
            if (idOrcamento != 0) {
                gerarListaInsumos();
            } else {
                JOptionPane.showMessageDialog(null, " Não foi possível localizar o orçamento. Verifique se o orçamento já foi salvo.", this.getTitle(), JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_jButton7ActionPerformed

    private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
        buscarTabelaInsumoOrcamento();
    }//GEN-LAST:event_jButton8ActionPerformed

    private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed
        ImprimirTabela imprimirTabela = new ImprimirTabela();
        imprimirTabela.gerarPdf(tableModelInsumoOrcamento, "Lista de Insumos", "Tabela de Insumos");
    }//GEN-LAST:event_jButton9ActionPerformed

    private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed
        ImprimirTabela imprimirTabela = new ImprimirTabela();
        imprimirTabela.gerarExcel(tableModelInsumoOrcamento, "Lista de Insumos", "Tabela de Insumos");
    }//GEN-LAST:event_jButton10ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.ButtonGroup buttonGroup2;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton10;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JButton jButton7;
    private javax.swing.JButton jButton8;
    private javax.swing.JButton jButton9;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JFormattedTextField jFormattedTextField1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel44;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JList jList2;
    private javax.swing.JList jList4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JRadioButton jRadioButton1;
    private javax.swing.JRadioButton jRadioButton2;
    private javax.swing.JRadioButton jRadioButton3;
    private javax.swing.JRadioButton jRadioButton4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    private javax.swing.JTextArea jTextArea2;
    private javax.swing.JTextField jTextField10;
    private javax.swing.JTextField jTextField13;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;
    private javax.swing.JTextField jTextField7;
    private javax.swing.JTextField jTextField8;
    private javax.swing.JTextField jTextField9;
    // End of variables declaration//GEN-END:variables
}
